package com.credit.management.system.util;


import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.credit.management.system.model.Page;




@Component
public class MyBatisPaginate {

	@Autowired
	private SqlSessionFactory sqlSessionFactory;
	/**
	 * 
	 * @param page 带有参数:page.getPageSize(),page.getPageNum()
	 * @param nameSpace_id ,工作空间.id
	 * @return
	 */
	public Page executeQueryPage(Page page,String nameSpace_id){
		SqlSession session=null;
		session=sqlSessionFactory.openSession();
		Map<String,Object> params=page.getParams();
//		if(params.size()>0&&params.containsKey("pname")){
//			
//			System.out.println("params.get('pname'):"+params.get("pname"));
//		}
		//new RowBounds(page.getPageNum(), page.getPageSize())不用datatables时，这里放的是page.getStartIndex(),因为controller那边
		//传给我们的是pageNum,需要我们在page类中计算，用了datatables时controller传给我们的是startIndex，不需要我们进行计算；
		List list=session.selectList(nameSpace_id,params ,new RowBounds(page.getStartIndex(), page.getPageSize()));		
		//List list2=session.selectList(nameSpace_id,params);		
		Integer total=getFoundRows(session);
		//sInteger total=list2.size();
		page.setTotal(total);
		page.setList(list);	
		session.close();
		return page;
	}
	/**
	 * 返回总条数
	 * @param session
	 * @return
	 */
	private int getFoundRows(SqlSession session) {
			int r = 0;
			try {
				Statement sm1;
				sm1 = session.getConnection().createStatement();
				ResultSet rs1 = sm1.executeQuery("select FOUND_ROWS() total");
				if (rs1.next()) {
					r = rs1.getInt(1);
				}
				sm1.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		return r;
	}
}
